﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace DuiBa.Core
{
    public static class Commond
    {
        /// <summary>
        /// 生成URL参数字符串
        /// </summary>
        /// <param name="urlParams"></param>
        /// <returns></returns>
        public static string GenerateUrlParams(Dictionary<string, string> urlParams)
        {
            var paramArr = urlParams.Select(param => string.Format("{0}={1}", param.Key, HttpUtility.UrlEncode(param.Value, Encoding.UTF8))).ToArray();
            return string.Join("&", paramArr);
        }
        /// <summary>
        /// 参数生成MD5
        /// </summary>
        /// <param name="paramsDic"></param>
        /// <returns></returns>
        public static string GenerateParamASCMD5(Dictionary<string, string> paramsDic)
        {
            var t = paramsDic.OrderBy(u => u.Key).ToList();
            var valArr = paramsDic.OrderBy(u => u.Key).Select(u => u.Value).ToArray();
            var rel = string.Join("", valArr);
            return GenerateMD5(rel).ToLower();
        }
        public static string GenerateParamASCMD5(string appSecret, Dictionary<string, string> paramsDic)
        {
            paramsDic.Add("appSecret", appSecret);
            var rel = GenerateParamASCMD5(paramsDic);
            paramsDic.Remove("appSecret");
            return rel;
        }
        public static string GenerateMD5(string str)
        {
            MD5 md5 = MD5.Create();
            byte[] bytes = md5.ComputeHash(Encoding.UTF8.GetBytes(str));
            StringBuilder result = new StringBuilder();
            for (int i = 0; i < bytes.Length; i++)
            {
                string hex = bytes[i].ToString("X");
                if (hex.Length == 1)
                {
                    result.Append("0");
                }
                result.Append(hex);
            }
            return result.ToString();
        }
        public static long ToTimesTamp(this DateTime dt)
        {
            TimeSpan ts = dt.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalMilliseconds);
        }
        public static string HttpGetResponse(string url)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();
            return retString;
        }
    }
}
